package com.security.demo.entity;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * UserDetails 为 Spring Security 系统类
 */
@Data
public class UserInfo implements UserDetails, Serializable {
    private Integer userId;
    private String userName;
    private String password;
    private Integer status;
    private Integer locked;
    private List<Role> roles;

    /**
     * 获取用户的所有角色
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            // 可以在数据库添加角色时，以 ROLE_ 开头，这样就不用拼加 ROLE_ 了
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
        }
        return authorities;
    }

    /**
     * 指定用户名字段
     */
    @Override
    public String getUsername() {
        return userName;
    }

    /**
     * 指定密码字段
     */
    @Override
    public String getPassword() {
        return password;
    }

    /**
     * 账户是否可用
     */
    @Override
    public boolean isEnabled() {
        return status == 1;
    }

    /**
     * 账号是否锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return locked == 0;
    }

    /**
     * 账号是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
}
